package lev01_beginnerClass.class05_comp;

import java.util.Arrays;

public class L01_Comp {


    public static void main(String[] args) {
        int maxlen = 50;
        int maxvalue = 100;
        for(int i = 0;i < 1000;i++){
            int[] arr = generateRandomArr(maxlen, maxvalue);
            int[] temp = copyArray(arr);
            selectionSort(arr);
            if(!issorted(arr)){
                System.out.println(Arrays.toString(temp));
                System.out.println("sort happend false");
                break;
            }


        }
    }

    /**
     * selection sort
     * @param arr
     */
    public static void selectionSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }


    /**
     * return array with length 0 - maxlen-1,and range:0-maxvalue-1;
     * @param maxlen
     * @param maxvalue
     * @return
     */
    public static int[] generateRandomArr(int maxlen,int maxvalue){
        int len = (int)(Math.random()*maxlen);
        int[] arr = new int[len];
        for(int i = 0;i < len;i++){
            arr[i] = (int)(Math.random()*maxvalue);
        }
        return arr;
    }

    //copy array
    public static int[] copyArray(int[] arr){
        int[] ans = new int[arr.length];
        for(int i = 0;i<arr.length;i++){
            ans[i] = arr[i];
        }
        return ans;
    }

    /**
     * judge array whether or not is sorted;
     * @param arr
     * @return
     */
    public static  boolean issorted(int[] arr){
        if(arr.length == 1){
            return  true;
        }
        for(int i = 1;i < arr.length;i++){
            if(arr[i] < arr[i-1]){
                return false;
            }
        }
        return true;
    }







}
